package cn.admin.configcenter.configservice.domain;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.Iterator;
import java.util.List;

public class PaginationHelper<E> {

	public Page<E> fetchPage(JdbcTemplate jdbcTemplate, String sqlCountRows,
	                         String sqlFetchRows, Object[] args, int pageNo, int pageSize, RowMapper<E> rowMapper) {
		if (pageNo > 0 && pageSize > 0) {
			Integer rowCount = jdbcTemplate.queryForObject(sqlCountRows,args,
					Integer.class);
			if (rowCount == null) {
			    throw new NullPointerException("rowCount is null");
            }
			int pageCount = rowCount / pageSize;
			if (rowCount > pageSize * pageCount) {
				++pageCount;
			}

			Page<E> page = new Page<>();
			page.setCurrentPage(pageNo);
			page.setTotalSize(rowCount);
			int startRow = (pageNo - 1) * pageSize;
			String selectSQL = sqlFetchRows + " OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY";
			List<E> result = jdbcTemplate.query(selectSQL, args, rowMapper);
            for (E aResult : result) {
                page.getResult().add(aResult);
            }

			return page;
		} else {
			throw new IllegalArgumentException("pageNo and pageSize must be greater than zero");
		}
	}

}
